package com.tc.itfarm.admin.action;

import com.tc.itfarm.api.util.EncoderUtil;
import com.tc.itfarm.model.User;
import com.tc.itfarm.service.SystemConfigService;
import com.tc.itfarm.web.biz.LoginBiz;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin")
public class AdminLoginAction{

	private static final Logger logger = LoggerFactory.getLogger(AdminLoginAction.class);
	
	@Resource
	private LoginBiz loginBiz;
	@Resource
	private SystemConfigService systemConfigService;

	@RequestMapping("toLogin")
	public String toLogin(HttpServletRequest request) {
		request.getSession().setAttribute("systemConfig", systemConfigService.selectAll().get(0));
		return "login/admin_index";
	}

	@RequestMapping("login")
	public String login(User user, HttpServletRequest request, ModelMap model) {
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), EncoderUtil.md5(user.getPassword()));
		token.setRememberMe(true);
		try{
			currentUser.login(token);
		} catch (IncorrectCredentialsException e) {
			logger.error(e.getMessage());
			model.addAttribute("message","密码错误!");
			return "login/admin_index";
		} catch (AuthenticationException e) {
			logger.error(e.getMessage());
			model.addAttribute("message",e.getMessage());
			return "login/admin_index";
		}

		if (currentUser.isAuthenticated()) {
			request.getSession().setAttribute("user", loginBiz.getCurUser());
		} else {
			return "login/admin_index";
		}
		return "redirect:index.do";
	}
	
	@RequestMapping("loginOut")
	public String loginOut(HttpServletRequest request) {
		loginBiz.userLoginOut();
		request.getSession().invalidate();
		return "login/login";
	}
	
}
